<template>
  <div class="battle-block" :class="{ 'is-winner': isWinner }">
    <div class="block-header" :class="{ 'game-over': isGameOver }">
      <!-- 状态 -->
      <div class="result" v-if="isGameOver">
        {{ resultText }}
      </div>

      <!-- 金额 -->
      <div class="user-info-amount" :class="{ 'is-show': amount > 0 }">
        <img src="@/static/img/battle/diamond.png" />
        <count-to :number="amount"></count-to>
        <span class="current-skin-price" :class="{ 'is-show': isShowSkinPrice }"
          >+{{ price }}</span
        >
      </div>

      <!-- 已就位/等待 -->
      <div class="status" v-if="text">
        <div class="status-text">{{ text }}</div>
        <img v-if="user" src="@/static/img/battle/ready.png" />
        <img v-else src="@/static/img/battle/wait1.png" class="icon-wait" />
      </div>
    </div>

    <div class="block-detail">
      <div class="skin-list-wrapper" ref="skinListWrapperRef" v-show="room.status === 1">
        <img src="@/static/img/battle/skin-list-bg.png" />
        <img src="@/static/img/battle/skin-list-bg.png" />

        <skin-list :skin-list="boxSkinList" ref="skinListRef"></skin-list>
      </div>

      <div class="user-info">
        <template v-if="user">
          <div style="width: 100%">
            <img class="user-avatar" :src="user.avatar" />
            <span class="nickname text-overflow">{{ user.nickname }}</span>
          </div>
          <!-- <div
            style="width: 100%"
            :class="{ 'is-show': room.status === 1 && amount > 0 }"
            class="user-info-amount"
          >
            <img src="@/static/img/battle/diamond.png" />
            <count-to :number="amount"></count-to>
          </div> -->
        </template>

        <v-btn
          v-else
          color="info"
          @click="handleClickButton"
          :size="isMobile ? 'small' : void 0"
          >{{ buttonText }}</v-btn
        >
      </div>
    </div>

    <div class="block-skin-list" :class="{ solo: room.num === 2 }">
      <battle-skin-item
        v-for="award in listRecords"
        :key="award.skin_id"
        :award="award"
      ></battle-skin-item>
    </div>
    <confirm-box ref="confirmBox"></confirm-box>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  PropType,
  computed,
  ref,
  nextTick,
  reactive,
  toRefs,
} from "vue";
import BattleSkinItem from "../BattleSkinItem.vue";
import ConfirmBox from "../ConfirmBox.vue";
import type {
  BattleUserInfo,
  BattleRoomInfo,
  BattleAward,
  BattleRoundData,
} from "../../services";
import { SkinItem } from "@/types";
import SkinList from "./SkinList.vue";
import { shuffle } from "@/utils";
import CountTo from "@/components/count-to/index.vue";
import { UserBattleRole } from "../../services";
import { emitter } from "@/libs";

export default defineComponent({
  setup(props, { emit }) {
    const { round: currentRound } = props;

    const inAnimation = ref(false);

    const state = reactive({
      boxSkinList: [] as SkinItem[],
      skinListWrapperRef: void 0 as any,
      skinListRef: void 0 as any,
      confirmBox: void 0 as any,
      price: 0,
      currentSkin: {} as SkinItem,
      falseRound: currentRound,
      isGameOver: computed(() => {
        return props.room.status === 2;
      }),
      text: computed(() => {
        const { user, room } = props;
        if (!user) {
          return "等待";
        }

        const { status } = room;
        if (status === 0) {
          // 等待中
          return "已就位";
        }
        return "";
      }),
      isWinner: computed(() => {
        const { user } = props;
        return user?.winner === 1 || user?.winner === 2;
      }),
      resultText: computed(() => {
        const { user } = props;
        if (!user) return "";

        const { winner } = user;

        if (winner === 1) {
          return "胜利";
        }

        if (winner === 2) {
          return "平局";
        }

        return "失败";
      }),
      isShowSkinPrice: computed(() => {
        return props.room.status === 1 && !inAnimation.value && state.price;
      }),
    });

    // 开始动画
    const start = (data: BattleRoundData) => {
      const { battle_record } = data;
      const { user, skinList } = props;

      if (!skinList.length) {
        console.error("盒子里没饰品", skinList);
        return;
      }

      if (!user) {
        console.error("该列无用户");
        return;
      }

      const record = battle_record.find((record) => record.user_id === user.user_id);

      if (!record) {
        console.error("开箱结果匹配失败", user.user_id, battle_record.slice());
        return;
      }

      inAnimation.value = true;

      let list: SkinItem[] = [];
      const padding = 60;
      const offset = 2;

      while (list.length !== padding) {
        list.push(...skinList.slice(0, padding - list.length));
      }

      // 寻找目标饰品
      const skin = skinList.find((skin) => skin.skin_id === record.skin_id);
      if (!skin) {
        console.error("没有找到目标饰品", record.skin_id, skinList.slice());
        return;
      }

      list = shuffle(list);
      list[padding - offset] = skin;

      state.currentSkin = skin;
      state.boxSkinList = list;

      setTimeout(() => {
        state.price = record?.skin_price;

        state.skinListRef
          .scroll(state.skinListWrapperRef.clientHeight, offset)
          .then(() => {
            state.falseRound++;
            inAnimation.value = false;
          });
      }, 100);
    };

    const listRecords = computed(() => {
      const { awards, comfortAward } = props;

      if (state.isGameOver) {
        return state.isWinner ? awards.slice() : [comfortAward!];
      }

      return awards.slice(0, state.falseRound);
    });

    return {
      listRecords,

      handleAddRobot: () => {
        emit("add-robot");
      },

      handleClickButton() {
        const { userRole, hasRobot } = props;
        if (userRole === UserBattleRole.Owner) {
          if (hasRobot) {
            // 复制链接
            emit("share");
          } else {
            emit("join-battle", true);
          }
        }

        if (userRole === UserBattleRole.Participant) {
          // 复制链接
          emit("share");
        }

        if (userRole === UserBattleRole.Audience) {
          // 加入房间
          //密码
          if (props.room.has_password) {
            state.confirmBox
                    .showInput("该房间需要密码才能进入")
                    .then((code) => {
                      emit("join-battle", false, code);
                    });
          }else {
            emit("join-battle", false, '');
          }
        }
        if (userRole === UserBattleRole.Tourist) {
          // 登录
          emitter.emit("login");
        }
      },

      start,
      amount: computed(() => {
        return listRecords.value.reduce((amount, next) => {
          return amount + next.skin_price;
        }, 0);
      }),

      buttonText: computed(() => {
        const { userRole, user, hasRobot } = props;

        if (user) return "";

        switch (userRole) {
          case UserBattleRole.Owner:
            if (hasRobot) return "分享链接";
            return "添加机器人";
          case UserBattleRole.Participant:
            return "分享链接";
          case UserBattleRole.Audience:
            return "参加";
          case UserBattleRole.Tourist:
            return "登录";
          default:
            console.warn("异常角色: ", userRole);
            return "";
        }
      }),

      ...toRefs(state),
      isMobile: window.screen.width <= 600,
    };
  },

  components: {
    BattleSkinItem,
    SkinList,
    CountTo,
    ConfirmBox
  },

  props: {
    user: {
      type: Object as PropType<BattleUserInfo>,
      default: null,
    },
    room: {
      type: Object as PropType<BattleRoomInfo>,
      default: null,
    },
    awards: {
      type: Array as PropType<BattleAward[]>,
      default: () => [],
    },
    skinList: {
      type: Array as PropType<SkinItem[]>,
      default: () => [],
    },
    userRole: {
      type: Number as PropType<UserBattleRole>,
    },
    round: {
      type: Number,
      default: 0,
    },
    comfortAward: {
      type: Object as PropType<BattleAward>,
    },
    hasRobot: Boolean,
  },
});
</script>

<style scope lang="scss">
.battle-block {
  flex: 1;
  overflow: hidden;

  &.is-winner {
    .result {
      color: #ffed47;
    }

    .block-detail {
      border-color: #ffed47;

      &::after {
        background: linear-gradient(180deg, rgba(255, 237, 71, 0) 0%, #ffec41 100%);
      }
    }

    .block-header {
      &::before {
        background: url(@/static/img/battle/battle-status-winner.png);
        background-size: cover;
      }
    }
  }
}

.block-header {
  text-align: center;
  color: #ffffff;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
  padding: 10px 0;

  &.game-over {
    &::before {
      content: "";
      background: url(@/static/img/battle/battle-status.png);
      background-size: cover;
      width: 115px;
      height: 115px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 0;
    }
  }

  > * {
    z-index: 2;
  }

  .result {
    font-size: 24px;
  }

  .status {
    text-align: center;
    margin-bottom: 14px;

    .status-text {
      font-size: 18px;
      margin-bottom: 15px;
    }

    img {
      width: 50px;
    }

    .icon-wait {
      animation: rotate 3s linear infinite;
    }
  }

  .block-amount {
    font-size: 16px;
    display: flex;
    align-items: center;
    margin-top: 12px;

    img {
      width: 23px;
      margin-right: 5px;
    }
  }
}

.block-detail {
  position: relative;
  border-bottom: 2px solid #8e7eed;
  margin-top: 7px;
  // padding-bottom: 31px;
  display: flex;
  flex-direction: column;
  min-height: 146px;

  &::after {
    content: "";
    background: linear-gradient(180deg, rgba(142, 126, 237, 0) 0%, #8271e5 100%);
    opacity: 0.2;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    position: absolute;
    z-index: 0;
  }

  .skin-list-wrapper {
    padding: 0 29px;
    margin-bottom: 15px;
    position: relative;
    overflow: hidden;
    max-height: 230px;
    box-sizing: border-box;

    > img {
      width: 100%;

      &:first-child {
        opacity: 0;
        z-index: -1;
      }

      &:nth-child(2) {
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        z-index: 10;
      }
    }

    .skin-list {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      z-index: 2;
      text-align: center;
      transition: top 3.5s cubic-bezier(0, 0, 0.01, 1);

      img {
        width: 50%;
      }
    }
  }

  .user-info {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: auto;
    height: 80px;
    z-index: 1;
    flex-direction: column;

    > * {
      display: flex;
      align-items: center;
      justify-content: center;
      flex: none;
    }

    .user-avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      margin-right: 6px;
    }

    .nickname {
      font-size: 18px;
      color: rgba(255, 255, 255, 0.5);
    }
  }
}

.user-info-amount {
  font-size: 16px;
  margin-top: 10px;
  transition: height 0.3s linear;
  display: flex;
  align-items: center;
  height: 0;
  position: relative;
  overflow: hidden;

  &.is-show {
    height: 26px;
    overflow: initial;
  }

  img {
    width: 23px;
    margin-right: 5px;
  }

  .current-skin-price {
    position: absolute;
    top: 50%;
    right: -10px;
    transform: translate(100%, -50%);
    color: #7affed;
    opacity: 0;
    transition: opacity 0.1s linear;

    &.is-show {
      opacity: 1;
    }
  }
}

.block-skin-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  margin-top: 10px;

  &.solo {
    justify-content: flex-start;

    > * {
      width: 33%;
      margin-right: 1px;
    }
  }

  > * {
    width: calc(50% - 1px);
    margin-top: 2px;
  }
}

@keyframes rotate {
  50% {
    transform: rotate(0);
  }

  100% {
    transform: rotate(360deg);
  }
}
</style>

<style scoped lang="scss">
@media screen and (max-width: 612px) {
  .battle-block {
    .block-header {
      &::before {
        width: 90px;
        height: 90px;
      }

      .result {
        font-size: 12px;
      }

      .status {
        .status-text {
          font-size: 12px;
        }
      }
    }

    .user-info {
      height: 50px;

      .user-avatar {
        width: 24px;
        height: 24px;
        margin-right: 2px;
      }

      .nickname {
        font-size: 12px;
      }
    }
  }

  .block-skin-list {
    margin-top: 1px;

    > * {
      width: 100%;
      margin-top: 2px;
    }
  }

  .block-amount {
    font-size: 12px;

    img {
      width: 14px;
    }
  }

  .block-detail {
    min-height: 60px;

    .skin-list-wrapper {
      padding: 0 10px;
    }
  }

  .user-info-amount {
    font-size: 12px;
    margin-top: 5px;

    &.is-show {
      height: 26px;
    }

    img {
      width: 14px;
      margin-right: 5px;
    }
  }
}
</style>
